<template>
  <div class="permissions-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>
            新增权限
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" inline class="search-form">
        <el-form-item label="权限名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入权限名称"
            clearable
            @keyup.enter="fetchPermissions"
          />
        </el-form-item>
        <el-form-item label="资源">
          <el-input
            v-model="queryParams.resource"
            placeholder="请输入资源"
            clearable
            @keyup.enter="fetchPermissions"
          />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
            <el-option label="菜单" value="MENU" />
            <el-option label="按钮" value="BUTTON" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchPermissions">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 权限树表格 -->
      <el-table
        :data="permissionTree"
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        border
      >
        <el-table-column prop="name" label="权限名称" min-width="200" />
        <el-table-column prop="resource" label="资源" width="120" />
        <el-table-column prop="action" label="操作" width="100" />
        <el-table-column prop="type" label="类型" width="80">
          <template #default="{ row }">
            <el-tag :type="row.type === 'MENU' ? 'primary' : 'success'">
              {{ row.type === 'MENU' ? '菜单' : '按钮' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" width="150" />
        <el-table-column prop="visible" label="可见" width="80">
          <template #default="{ row }">
            <el-tag :type="row.visible ? 'success' : 'danger'">
              {{ row.visible ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link size="small" @click="editPermission(row)">
              编辑
            </el-button>
            <el-button link size="small" @click="addChild(row)">
              添加子权限
            </el-button>
            <el-button link size="small" type="danger" @click="deletePermission(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 权限表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑权限' : '新增权限'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="permissionForm"
        :rules="permissionRules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="资源" prop="resource">
          <el-input v-model="permissionForm.resource" placeholder="请输入资源标识" />
        </el-form-item>
        <el-form-item label="操作" prop="action">
          <el-input v-model="permissionForm.action" placeholder="请输入操作标识" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="permissionForm.type" placeholder="请选择权限类型">
            <el-option label="菜单" value="MENU" />
            <el-option label="按钮" value="BUTTON" />
          </el-select>
        </el-form-item>
        <el-form-item label="路径" v-if="permissionForm.type === 'MENU'">
          <el-input v-model="permissionForm.path" placeholder="请输入菜单路径" />
        </el-form-item>
        <el-form-item label="组件" v-if="permissionForm.type === 'MENU'">
          <el-input v-model="permissionForm.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="图标" v-if="permissionForm.type === 'MENU'">
          <el-input v-model="permissionForm.icon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="permissionForm.sort" :min="0" />
        </el-form-item>
        <el-form-item label="是否可见">
          <el-switch v-model="permissionForm.visible" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="permissionForm.description"
            type="textarea"
            placeholder="请输入权限描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePermission">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

interface Permission {
  id?: number
  name: string
  resource: string
  action: string
  description: string
  type: 'MENU' | 'BUTTON'
  path?: string
  component?: string
  icon?: string
  sort: number
  visible: boolean
  parentId?: number
  children?: Permission[]
}

const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

const queryParams = reactive({
  name: '',
  resource: '',
  type: ''
})

const permissionTree = ref<Permission[]>([])

const permissionForm = reactive<Permission>({
  name: '',
  resource: '',
  action: '',
  description: '',
  type: 'MENU',
  path: '',
  component: '',
  icon: '',
  sort: 0,
  visible: true,
  parentId: undefined
})

const permissionRules = {
  name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
  resource: [{ required: true, message: '请输入资源标识', trigger: 'blur' }],
  action: [{ required: true, message: '请输入操作标识', trigger: 'blur' }],
  type: [{ required: true, message: '请选择权限类型', trigger: 'change' }]
}

const fetchPermissions = async () => {
  loading.value = true
  try {
    const response = await request.get('/permissions/tree')
    permissionTree.value = response.data || []
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

const showCreateDialog = () => {
  resetForm()
  isEdit.value = false
  dialogVisible.value = true
}

const editPermission = (permission: Permission) => {
  Object.assign(permissionForm, { ...permission })
  isEdit.value = true
  dialogVisible.value = true
}

const addChild = (parent: Permission) => {
  resetForm()
  permissionForm.parentId = parent.id
  isEdit.value = false
  dialogVisible.value = true
}

const savePermission = async () => {
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      await request.put(`/permissions/${permissionForm.id}`, permissionForm)
      ElMessage.success('更新权限成功')
    } else {
      await request.post('/permissions', permissionForm)
      ElMessage.success('创建权限成功')
    }
    
    dialogVisible.value = false
    fetchPermissions()
  } catch (error) {
    ElMessage.error('保存权限失败')
  }
}

const deletePermission = async (permission: Permission) => {
  try {
    await ElMessageBox.confirm(`确定要删除权限"${permission.name}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.delete(`/permissions/${permission.id}`)
    ElMessage.success('删除权限成功')
    fetchPermissions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除权限失败')
    }
  }
}

const resetForm = () => {
  Object.assign(permissionForm, {
    id: undefined,
    name: '',
    resource: '',
    action: '',
    description: '',
    type: 'MENU',
    path: '',
    component: '',
    icon: '',
    sort: 0,
    visible: true,
    parentId: undefined
  })
  formRef.value?.resetFields()
}

const resetQuery = () => {
  Object.assign(queryParams, {
    name: '',
    resource: '',
    type: ''
  })
  fetchPermissions()
}

onMounted(() => {
  fetchPermissions()
})
</script>



